package com.market.controller;

import com.market.entity.Role;
import com.market.entity.User;
import com.market.service.RoleService;
import com.market.service.UserService;
import com.market.utils.PageResult;
import com.market.utils.SessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@RestController
@RequestMapping("/user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private RoleService roleService;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Map<String, Object> login(
            @RequestParam String userCode, 
            @RequestParam String passWord,
            HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        logger.info("接收到登录请求 - 用户: {}", userCode);
        
        try {
            // 记录请求头部信息，帮助调试
            String origin = request.getHeader("Origin");
            String contentType = request.getHeader("Content-Type");
            String method = request.getMethod();
            logger.info("登录请求详情 - 方法: {}, Origin: {}, Content-Type: {}", 
                    method, origin, contentType);
            
            User user = userService.login(userCode, passWord);
            if (user != null) {
                // 将用户信息存入session
                HttpSession session = request.getSession(true);
                String sessionId = session.getId();
                session.setAttribute(SessionUtil.USER_SESSION, user);
                
                logger.info("用户登录成功 - 用户名: {}, ID: {}, 角色: {}, 会话ID: {}", 
                        user.getUserName(), user.getId(), user.getUserRole(), sessionId);
                
                // 不设置过期时间，使用会话级session，关闭浏览器后自动失效
                
                result.put("flag", true);
                result.put("message", "登录成功");
                result.put("data", user);
                
                // 设置响应头，确保CORS工作正常
                HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
                if (response != null && origin != null) {
                    response.setHeader("Access-Control-Allow-Origin", origin);
                    response.setHeader("Access-Control-Allow-Credentials", "true");
                    logger.info("已设置响应的CORS头");
                }
            } else {
                logger.warn("登录失败 - 用户名或密码错误: {}", userCode);
                result.put("flag", false);
                result.put("message", "用户名或密码错误");
            }
        } catch (Exception e) {
            logger.error("登录异常", e);
            result.put("flag", false);
            result.put("message", "登录失败: " + e.getMessage());
        }
        
        logger.info("登录响应: {}", result);
        return result;
    }
    
    /**
     * 更新用户信息
     */
    @PostMapping("/update")
    public Map<String, Object> update(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean updated = userService.update(user);
            if (updated) {
                result.put("flag", true);
                result.put("message", "更新用户信息成功");
                result.put("data", user);
            } else {
                result.put("flag", false);
                result.put("message", "更新用户信息失败");
            }
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "更新用户信息失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 更新密码
     */
    @PostMapping("/updatePassword")
    public Map<String, Object> updatePassword(
            @RequestParam Long id, 
            @RequestParam String userPassword,
            @RequestParam String newPwd) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean updated = userService.updatePassword(id, userPassword, newPwd);
            if (updated) {
                result.put("flag", true);
                result.put("message", "密码修改成功");
            } else {
                result.put("flag", false);
                result.put("message", "密码修改失败，可能是旧密码错误");
            }
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "密码修改失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 用户注销
     */
    @GetMapping("/logout")
    public Map<String, Object> logout(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        // 清除session
        HttpSession session = request.getSession();
        session.removeAttribute(SessionUtil.USER_SESSION);
        session.invalidate();
        
        result.put("flag", true);
        result.put("message", "注销成功");
        return result;
    }
    
    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/current")
    public Map<String, Object> getCurrentUser(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        // 获取当前登录用户
        User user = SessionUtil.getCurrentUser();
        
        if (user != null) {
            result.put("flag", true);
            result.put("data", user);
        } else {
            result.put("flag", false);
            result.put("message", "未登录或登录已过期");
        }
        return result;
    }

    /**
     * 分页查询用户
     */
    @GetMapping("/search")
    public Map<String, Object> search(
            @RequestParam(required = false) String userName,
            @RequestParam(required = false) String userCode,
            @RequestParam(required = false, defaultValue = "1") Integer currentPage,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        logger.info("接收到用户查询请求 - userName: {}, userCode: {}, currentPage: {}, pageSize: {}", 
                userName, userCode, currentPage, pageSize);
        
        try {
            PageResult<User> pageResult = userService.findByPage(userName, userCode, currentPage, pageSize);
            
            // 记录查询结果
            int resultCount = pageResult.getList() != null ? pageResult.getList().size() : 0;
            logger.info("用户查询成功，返回 {} 条记录", resultCount);
            
            if (resultCount == 0) {
                logger.warn("用户查询返回空结果");
            }
            
            result.put("flag", true);
            result.put("data", pageResult.getList());
            result.put("total", pageResult.getTotalCount());
            result.put("currentPage", pageResult.getCurrentPage());
            result.put("pageSize", pageResult.getPageSize());
            result.put("totalPages", pageResult.getTotalPages());
            
        } catch (Exception e) {
            logger.error("用户查询失败", e);
            result.put("flag", false);
            result.put("message", "搜索用户失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 添加用户
     */
    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody User user) {
        return userService.add(user);
    }
    
    /**
     * 更新用户状态
     */
    @PostMapping("/updateStatus")
    public Map<String, Object> updateStatus(
            @RequestParam Long id, 
            @RequestParam Integer status) {
        return userService.updateStatus(id, status);
    }
    
    /**
     * 根据ID查询用户详情
     */
    @GetMapping("/{id}")
    public Map<String, Object> getById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            User user = userService.findById(id);
            if (user != null) {
                // 脱敏处理
                user.setUserPassword(null);
                user.setSalt(null);
                
                result.put("flag", true);
                result.put("data", user);
            } else {
                result.put("flag", false);
                result.put("message", "未找到ID为" + id + "的用户");
            }
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "获取用户详情失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 获取所有用户角色列表（用于用户管理中的角色选择）
     */
    @GetMapping("/roles")
    public Map<String, Object> getRoles() {
        Map<String, Object> result = new HashMap<>();
        try {
            // 这里需要注入RoleService
            List<Role> roles = roleService.findAll();
            result.put("flag", true);
            result.put("data", roles);
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "获取角色列表失败: " + e.getMessage());
        }
        return result;
    }
}
